package com.guli.gulimall.product.service.impl;

import com.guli.gulimall.product.dao.AttrDao;
import com.guli.gulimall.product.dao.CategoryDao;
import com.guli.gulimall.product.entity.AttrEntity;
import com.guli.gulimall.product.vo.AttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.AttrGroupDao;
import com.guli.gulimall.product.entity.AttrGroupEntity;
import com.guli.gulimall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @SuppressWarnings("all")
    @Autowired
    private CategoryDao categoryDao;

    @SuppressWarnings("all")
    @Autowired
    private AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params,Long catelogId) {
        QueryWrapper<AttrGroupEntity> w = new QueryWrapper<>();
        if (!catelogId.equals(0L))
            w.eq("catelog_id",catelogId);
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                w
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrGroupVo> withattr(Long catelogId) {
        // 1.通过当前分类编号查询到分组信息

        QueryWrapper<AttrGroupEntity> w = new QueryWrapper<>();

        w.eq("catelog_id",catelogId);
        List<AttrGroupEntity> groupList = baseMapper.selectList(w);
        // 2.把数据库查询到的分组信息
        List<AttrGroupVo> collect = groupList.stream().map(item -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            // 每一个item就是数据库查询到的对象
            // 一定要保证数据要一致
            BeanUtils.copyProperties(item, attrGroupVo);
            // 拷贝结束后vo中还剩下attrs没有赋值
            // 3.查询每个分组下的规格参数
            QueryWrapper<AttrEntity> w2 = new QueryWrapper<>();
            // 3.1 分组编号
            w2.eq("attr_group_id", item.getAttrGroupId());
            // 3.2 属性是规格参数
            w2.eq("attr_type", 1);
            List<AttrEntity> attrEntities = attrDao.selectList(w2);
            attrGroupVo.setAttrs(attrEntities);
            return attrGroupVo;
        }).collect(Collectors.toList());

        return collect;
    }

}